<template>
  <div class="login-container">
    <div class="header-fix">
      <p>Giesecke+Devrient</p>
    </div>
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      autocomplete="on"
      label-position="left"
    >
      <div class="title-container-login">
        <h3 class="title-login">{{ $t("login.title") }}</h3>
        <lang-select class="set-language" />
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          :placeholder="$t('login.username')"
          name="username"
          type="text"
          tabindex="1"
          autocomplete="on"
        />
      </el-form-item>

      <el-tooltip
        v-model="capsTooltip"
        content="Caps lock is On"
        placement="right"
        manual
      >
        <el-form-item prop="password">
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginForm.password"
            :type="passwordType"
            :placeholder="$t('login.password')"
            name="password"
            tabindex="2"
            autocomplete="on"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
            @keyup.enter.native="handleLogin"
          />
          <span class="show-pwd" @click="showPwd">
            <svg-icon
              :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
            />
          </span>
        </el-form-item>
      </el-tooltip>
      <el-form-item prop="status">
        <SliderCheck
          :status="loginForm.status"
          :success-fun="handleSuccessFun"
          :error-fun="handleErrorFun"
          :start-text="$t('login.startText')"
          :success-text="$t('login.successText')"
        />
      </el-form-item>
      <el-button
        :loading="loading"
        type="primary"
        style="width: 100%; margin-bottom: 30px"
        @click.native.prevent="handleLogin"
        >{{ $t("login.logIn") }}</el-button
      >
      <div class="forget">
        <el-button type="text" style="color: #fff !important" @click="toPage"
          >Forget password？</el-button
        >
      </div>
    </el-form>
  </div>
</template>

<script>
// import { validUsername } from "@/utils/validate";
import { getProductGroupList } from "@/api/productGroup";
import LangSelect from "@/components/LangSelect";
// import SocialSign from './components/SocialSignin'
import SliderCheck from "./components/SliderCheck";
import shopers from "@/utils/shopers.js";
export default {
  name: "Login",
  components: { LangSelect, SliderCheck },
  data() {
    const validateUsername = (rule, value, callback) => {
      // if (!validUsername(value)) {
      //   callback(new Error("Please enter the correct user name"));
      // } else {
      //   callback();
      // }
      if (!value) {
        callback(new Error(this.$t("login.noName")));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error(this.$t("login.noPassword")));
      } else {
        callback();
      }
    };
    const validateStatus = (rule, value, callback) => {
      if (!value) {
        callback(new Error(this.$t("login.noSwipe")));
      } else {
        callback();
      }
    };
    return {
      Locked: false,
      loginForm: {
        username: "", // "cardconfig",
        password: "", // "123456",
        status: false,
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
        status: [
          { required: true, trigger: "blur", validator: validateStatus },
        ],
      },
      passwordType: "password",
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true,
    },
  },
  created() {
    // 缓存初始商户
    const merchantManagement = require("../../../mock/managements");
    if (!this.storage.get("shopers")) {
      this.storage.set("shopers", merchantManagement);
    }
  },
  mounted() {
    if (this.loginForm.username === "") {
      this.$refs.username.focus();
    } else if (this.loginForm.password === "") {
      this.$refs.password.focus();
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    toPage() {
      this.$router.push({ path: "unbind" });
    },
    // 滑块验证成功回调
    handleSuccessFun() {
      this.loginForm.status = true;
    },
    // 滑块验证失败回调
    handleErrorFun() {},

    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z";
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    handleLogin() {
      // 去掉空格
      this.loginForm.username = this.loginForm.username.replace(/\s+/g, "");
      const arr = this.storage.get("shopers") || []; // 商户数组
      // 用户是否被锁定
      let locked = false;
      if (this.loginForm.username === "management0") {
        this.storage.set("shopers", shopers);
        console.log("shopers===", shopers);
      } else {
        arr.forEach((item) => {
          if (item.account == this.loginForm.username) {
            locked = item.status;
          }
        });
        if (locked) {
          this.$message({
            message: this.$t("login.locked"),
            type: "warning",
          });
          return false;
        }
      }
      console.log("locked====", locked);
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          // 密码错误
          if (this.loginForm.username !== "admin") {
            let loginSucceed = false;
            arr.forEach((item) => {
              if (
                this.loginForm.password == item.password &&
                this.loginForm.username == item.account
              ) {
                this.storage.set("user", {
                  account: this.loginForm.username,
                  password: this.loginForm.password,
                });
                loginSucceed = true;
              }
            });
            if (!loginSucceed) {
              this.$message.error(this.$t("login.erroPass"));
              this.loading = false;
              return false;
            }
          }
          // 管理员账号改为admin
          const form = JSON.parse(JSON.stringify(this.loginForm));
          form.username =
            this.loginForm.username === "admin"
              ? "management0"
              : this.loginForm.username;

          this.$store
            .dispatch("user/login", form)
            .then(async () => {
              this.storage.set("sequence", this.$t("login.sequence"));
              this.storage.set("orderStatus", this.$t("login.orderStatus"));
              this.storage.set("types", this.$t("login.types"));
              // this.storage.set("imgList", []);
              const res = await getProductGroupList({ page: 1, limit: 999 });
              this.storage.set("productGroupList", res.data);

              // if (
              //   this.loginForm.username === "admin" ||
              //   this.loginForm.username === "shoper"
              // ) {
              this.$router.push({
                path: "/",
              });
              // } else {
              //   console.log("this.redirect==", this.redirect);
              //   console.log("this.otherQuery==", this.otherQuery);
              //   this.$router.push({
              //     path: "/commodityManagement/list",
              //   });
              // }

              this.loading = false;
            })
            .catch((err) => {
              console.log(err);
              this.loading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
  },
};
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container-login {
    position: relative;

    .title-login {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }

    .set-language {
      color: #fff;
      position: absolute;
      top: 3px;
      font-size: 18px;
      right: 0px;
      cursor: pointer;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
.forget {
  display: flex;
  justify-content: flex-end;
}
.header-fix {
  position: absolute;
  color: #ffffff;
  font-size: 35px;
  padding: 15px;
}
</style>
